package cn.itsource.wechart.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.Vo.LoginVo;
import cn.itsource.org.domain.User;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.org.service.IUserService;
import cn.itsource.wechart.mapper.WeChartMapper;
import cn.itsource.wechart.pojo.domain.WechartProperties;
import cn.itsource.wechart.pojo.domain.WxUser;
import cn.itsource.wechart.pojo.domain.dto.WechartTokenDto;
import cn.itsource.wechart.pojo.dto.BinderDto;
import cn.itsource.wechart.pojo.dto.WechartUserInfoDto;
import cn.itsource.wechart.service.WeChartService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
@Service
public class WeChartServiceImpl implements WeChartService {
    @Autowired
    private WechartProperties wechartProperties;
    @Autowired
    private WeChartMapper mapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisService redisService;
    @Override
    public String toLogin() {

//        https://open.weixin.qq.com/connect/qrconnect?appid=&redirect_uri=https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect
//        步骤一,跳转到扫描的页码
//        获取到授权网址url
        String url = wechartProperties.getAuthorizationCodeUrl();
//        进行url拼接操作
        String format = String.format(url, wechartProperties.getAppId(), wechartProperties.getRedirectUri(), IdUtil.fastSimpleUUID());
//        重定向到扫码页面
        System.out.println(format);
        return "redirect:" + format;

    }

    @Override
    public String callback(String code) {
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code
        //步骤二，通过code获取access_token
        String tokenUrl = wechartProperties.getTokenUrl();
//        拼接url
        String Url = String.format(tokenUrl, wechartProperties.getAppId(), wechartProperties.getAppSecrect(), code);
        //3.用java代码访问这个拼接好的url
        String s = HttpUtil.get(Url);
//        将数据封装到dto中
        WechartTokenDto wechartTokenDto = JSONObject.parseObject(s, WechartTokenDto.class);
        //步骤三，获取微信三方用户信息
        //1.获取url //https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s"
        String userinfoUrl = wechartProperties.getUserinfoUrl();
        //2.处理%s
        userinfoUrl = String.format(userinfoUrl, wechartTokenDto.getAccess_token(), wechartTokenDto.getOpenid());

        //3.发get请求
        String infoResult = HttpUtil.get(userinfoUrl);
        System.out.println(infoResult);//json串
        //4.解析json字符串，到dto中
        WechartUserInfoDto infoDto = JSONObject.parseObject(infoResult, WechartUserInfoDto.class);
        System.out.println(infoDto);

        //----------------------------上面是调用微信开放平台接口，下面把微信信息绑定平台账户----------------------------------------------------------------
        /**
         * openid在每个企业账户下，每个人是唯一的，同一个人在同一个企业账号下扫描openid就是独一无二的
         * 通过分析，得到3种情况进行处理
         *   1.通过openid在t_wxuser表拿不到数据源
         *     1.1新增t_wxuser的一行数据
         *     1.2去绑定页面进行绑定
         *   2.所有的数据都是ok的 t_wxuser有user_id  t_user有手机号
         *     1.2跳转到平台首页
         *   3.其他情况
         *      3.1全部去绑定页面（binder.html）
         */
        String binderHtmlUrl = "http://127.0.0.1:8081/binder.html";
//    获取openid数据
        String openid = infoDto.getOpenid();
        WxUser wxUser = mapper.findByOpenid(openid);
//        判断微信user是否存在
        if (wxUser==null){
            WxUser user = BeanUtil.copyProperties(infoDto, WxUser.class);
            //        入库
            mapper.insertSelective(user);
//            跳转到绑定页面
            return "redirect:"+binderHtmlUrl+"?openid="+openid;
        }
        //处理情况2
        Long userId = wxUser.getUserId();
        if (userId!=null){
        //1.查user对象
            User dbUser = userService.findOne(userId);
//            如果用户表数据完整则执行下步操作
            if (dbUser!=null&& StrUtil.isNotBlank(dbUser.getPhone())){
//                传递token和登录信息
//                生成token
                String token = IdUtil.fastSimpleUUID();
                LoginVo loginVo = new LoginVo();
                loginVo.setToken(token);
                redisService.setStringKeyAndValue(token,loginVo,30);
//                返回重定向前端主页,携带token和手机号
                return "redirect:http://localhost:8081/index.html?phone="+dbUser.getPhone()+"&token="+token;
            }
        }
//        处理情况3
//        其他情况全部重定向到绑定手机号页面
        return "redirect:"+binderHtmlUrl+"?openid="+openid;
    }


    /**
     * 绑定平台用户数据
     * @param binderDto
     * @return
     */
    @Override
    public AjaxResult binder(BinderDto binderDto) {
//        通过手机号获取用户对象
        String phone = binderDto.getPhone();
        User checkphone = userMapper.checkphone(phone);
        Long userId = null;
        //dbPhone不存在 1.新增user数据  2.拿到自增id  3.修改wxUser的user_id
        if (checkphone==null){
            User user = new User();
            user.setPhone(phone);
            user.md5Pwd();//加盐加密
            userMapper.insertSelective(user);
            userId = user.getId();
        }else{
            userId = checkphone.getId();
        }
        //存在，拿到userId,修改wxUser的user_id
        mapper.updateUserIdByOenid(userId,binderDto.getOpenid());
        //生成token，存到redis，返回页面
        String token = IdUtil.fastSimpleUUID();
        LoginVo loginVo = new LoginVo();
        loginVo.setPhone(phone);
        loginVo.setToken(token);
        redisService.setStringKeyAndValue(token,loginVo,30);

        return AjaxResult.createSuccess(loginVo);
    }
}